<?php
namespace control;
// 工作报告 - 周报
class workReportWeekClass extends adIndexClass
{
    private const page  = 'workReportWeek'; # 权限
    private const table = 'work_report'; # 数据表
    private const title = '工作周报';

    /*列表页-查询条件*/
    public function home()
    {
        $page = find([
            'table' => self::table,
            'field' => 'location, state',
            'where' => " type = '周报' AND stid = '".self::$stid."' "
        ]);
        $mark = [];
        foreach ((array) $page['array'] as $item) {
            $mark[$item['location']] = '';
        }
        $mark  = json_encode($mark, 320);
        if ($this->get('date')) {
            $date = $this->get('date');
        } else {
            $obj = new \DateTime();
            $obj->modify('this week');
            $date = $obj->format('Y-m-d');
        }
        $leftHtml = <<<EOT
        <div id="work-report-box"></div>
        <div class="work-report-date-box" id="work-report-date-box"> <span id="date-span1" class="date-span1"></span>-<span id="date-span2" class="date-span2"></span></div>
        <script>
        function replaceRightDetail(date, type=null){
            let api = root + 'control/adIndex.html?cla={$this->get('cla')}&fun=homeRight'
            $.post(api, { date: date, type: type}, function (data) {
                $('#container-detail').html(data.html)
            }, "json");
        }

        laydate.render({
            elem: '#work-report-box'
            ,format: "yyyy-MM-dd"
            ,btns: ['clear', 'now']
            ,trigger: 'click'
            ,showBottom: false
            ,value: '{$date}'
            ,position: 'static'
            ,ready: function(date) {
                onlyMonday()
                return this.changeData(date)
            }
            ,change: function() {
                return onlyMonday()
            }
            ,mark: {$mark}
            ,changeData: function(date) {
                // 修改数据
                let now = date.year+'-'+date.month+'-'+date.date,
                    end = this.addDate(now, 6)
                $('#work-report-date-box').show()
                $("#date-span1").html(now)
                $("#date-span2").html(end)
                return replaceRightDetail(now)
            }
            ,addDate: function (date, days) {
                var d = new Date(date);
                d.setDate(d.getDate() + days);
                var m = d.getMonth() + 1;
                m = m < 10 ? '0' + m : m;
                var dd = d.getDate();
                dd = dd < 10 ? '0' + dd : dd;
                return d.getFullYear() + '-' + m + '-' + dd;
            }
            ,done: function(value, date){
                return this.changeData(date)
            }
          });
        </script>
EOT;
        $html = <<<EOT
        <div class="work-report-container">
            <div class="container-left work-report-container-left" id="container-left">
                {$leftHtml}
            </div>
            <div class="container-right work-report-container-right" id="container-detail">
            </div>
        </div>
EOT;
        //返回
        return $this->homeFun($html);
    }

    public function homeRight()
    {
        $date = $this->post('date') ?? '';
        $where =  " type = '周报' AND stid = '".self::$stid."' AND  location = '$date'  ";
        $info = query(self::table, $where);
        if (empty($info['id'])) {
            return $this->editPage($where);
        } else {
            if ($this->post('type') == 'edit') {
                return $this->editPage($where);
            } else {
                return $this->detail($info['id']);
            }
        }
    }

    /**
     * 编辑页面
     *
     * @param $where
     * @return string
     */
    public function editPage($where): string
    {
        $info = query(self::table, $where);
        if (!$this->power(self::page, "see")) {
            $json['warn'] = L('person.table.nmzckzx');
        } else {
            $id       = $info['id'] ?: self::getId();
            $location = $info['location'] ?: $this->post('date');
            //生成页面
            $json['warn'] = 2;
            $json['html'] = $this->pageEdit([
                "table" => [
                    '基本信息' => [
                        [
                            must . L('person.table.bzgzcg') => textarea(['name' => "now", 'class' => 'text', 'value' => $info['now']]),
                        ],
                        [
                            L('person.table.xia_zhou_ji_hua') => textarea(['name' => "next", 'class' => 'text', 'value' => $info['next']]),
                        ],
                        [
                            L('person.table.qi_ta_shi_xiang') => textarea(['name' => "other", 'class' => 'text', 'value' => $info['other']]),
                        ],
                        [
                            L('person.table.fu_jian') => fileUploadClass::addFileComponent($id, self::title, self::page, self::page.'HomeRightForm'),
                        ],
                        [
                            L('person.table.shen_pi_ren') => L('person.table.zssj') . hidden(['name' => 'id', 'value' => $id]) . hidden(['name' => 'location', 'value' => $location]),
                        ],
                        [
                            '&nbsp' => '<button class="button left" onclick="subForm(\'' . $this->get('cla') . 'HomeRightForm\', root+\'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPageEdit\')">'.L('person.table.ti_jiao').'</button>'
                        ]
                    ]
                ],
            ]);
        }
        //返回
        return json_encode($json, 320);
    }

    /*成本表基本资料新增或修改-异步处理*/
    public function editPageEdit()
    {
        $id = $this->post('id') ?: self::getId();
        // 文件id
        $fileIdArr = $this->post('fileId');
        $field = [
            'location' => $this->post('location'),
            'now'      => $this->post('now'),
            'next'     => $this->post('next'),
            'other'    => $this->post('other'),
            'auditor'    => self::$staff['manager'],
        ];
        $annotation = [
            'location' => L('person.table.dqzq'),
            'now'      => L('person.table.bzgz'),
            'next'     => L('person.table.xia_zhou_ji_hua'),
            'other'    => L('person.table.qi_ta_shi_xiang'),
        ];
        $rules = [
            'location' => 'required',
            'now'      => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = $json['warn'] = L('person.table.weekReportEdit');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $orderNo = codeTemplateClass::generateCode(self::page,[
                    'table'   => self::table,
                    'prefix'  => 'RE' . date('Ymd'),
                    'default' => '001'
                ],$field);
                $field    = array_merge($field, [
                    'id'         => $id,
                    'orderNo'    => $orderNo,
                    'type'       => '周报',
                    'department' => self::findStaffDepartment(self::$stid),
                    'state'      => '草稿',
                    'stid'       => self::$stid,
                    'time'       => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                if (is_array($fileIdArr)) {
                    update([
                        'table' => 'file',
                        'field' => ['targetId' => $id],
                        'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                    ]);
                }
                //添加周志
                $text = str_replace(['{{staffName}}','{{location}}','{{id}}'],[$this->control['name'],$field['location'],$id],L('person.table.week_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&date=" . $field['location'];
            }
        }

        resp:
        return json_encode($json, 320);
    }

    public function detail($id)
    {
        $info = query(self::table, " id = '$id' ");
        if (!$this->power(self::page, "see")) {
            $json['warn'] = L('person.table.nmzckzx');
        } elseif (!$info['id']) {
            $json['warn'] = L('person.table.wzdcxx');
        } else {
            $data = [
                "id" => $info['id'],
            ];
            //按钮
            $button = [];
            if ($this->power(self::page, "del")) {
                $button[] = [
                    "name"  => L('person.table.shan_chu'),
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act" => 'del', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "edit")) {
                if ($info['state'] == '草稿') {
                    $button[] = [
                        "name" => L('person.table.bian_ji'),
                        "type" => "点击事件",
                        "fun"   => "replaceRightDetail('{$info['location']}', 'edit')",
                    ];
                    $button[] = [
                        "name" => L('person.table.ti_jiao'),
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun"   => "operate",
                        "post"  => ["act" => 'commit', "id" => $info['id'], 'state' => $info['state']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
            }
            //生成表单
            $data['html'] = $this->tableShow([
                L('person.table.zbxq')   => [
                    [
                        L('person.table.zhou_qi') => self::null($info['location']),
                    ],
                    [
                        L('person.table.bzgz') => pre($info['now']),
                    ],
                    [
                        L('person.table.xzgz') => pre($info['next']),
                    ],
                    [
                        L('person.table.qi_ta_shi_xiang') => pre($info['other']),
                    ],
                ],
                L('person.table.fu_jian') => [
                    [
                        fileUploadClass::showFile($info['id'], self::title)
                    ],
                ],
                L('person.table.xi_tong_xin_xi') => [
                    [
                        L('person.table.hbbh') => $info['orderNo'],
                        L('person.table.hbrbm') => $info['department'],
                        L('person.table.hui_bao_ren') => self::findStaff($info['stid']),
                    ],
                    [
                        L('person.table.shen_pi_ren') => self::findStaff($info['auditor']),
                        L('person.table.cjsj') => $info['time'],
                        L('person.table.hbsj') => $info['commitTime'],
                    ],
                    [
                        L('person.table.zhuang_tai') => $info['state'],
                        L('person.table.ping_ji') => $info['rate'],
                    ],
                ]
            ]);
            //生成页面
            $json['warn'] = 2;
            $json['html'] = "<div class='tab-box'>
                    <div class='tab-button'>".$this->tableShowButton($button)."</div>
                    <div class='tab-content'>".$data['html']."</div>
                </div>";
        }
        //返回
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $append = [];
        switch ($act) {
            case 'commit':
                $act = 'edit';
                $word = true;
                $title = L('person.table.commitReport');
                $function = 'commit';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg =  L('person.table.week_del_title');
                $title = 'workReportDelete';
                $function = 'isDelete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'append'   => $append,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 修改状态
     */
    public function commit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        $act = 'edit';
        $json = [];
        if (!$this->power(self::page, $act)) {
            $json['warn'] = L('person.table.nmzczxdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('person.table.nytjldmzxzn');
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 修改field
            $fieldKey = 'state';
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['id']) {
                    if (static::isNull(self::$staff['manager'])) {
                        $text .= str_replace(['{{location}}','{{id}}'],[$info['location'],$info['id']],L('person.table.week_commit_warn'))."<br>";
                        continue;
                    }
                    $fieldVlaue = ($info['state'] == '草稿') ? '待查看' : '草稿';
                    // 修改状态
                    static::update([
                        "table" => self::table,
                        'field' => [
                            $fieldKey    => $fieldVlaue,
                            'commitTime' => $this->time,
                            'auditor'=>self::$staff['manager'],
                        ],
                        "where" => $where
                    ]);
                    //添加记录
                    $text .=str_replace(['{{staffName}}','{{staffName}}','{{staffName}}'],[$this->control['name'],$info['location'],$info['id']],L('person.table.week_commit_text')). '<br>';
                    $x++;
                }
            }
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] =str_replace(['{{x}}'],[$x],L('person.table.week_commit_mag')).',详情请查看日志';
            $json['warn']     = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        resp:
        return json_encode($json, 320);
    }


    // 确认删除信息
    public function isDelete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('person.table.week_del_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('person.table.nytjldmzxzn');
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['id']) {
                    if ($info['state'] == '已查看') {
                        $text .=str_replace(['{{location}}','{{id}}'],[$info['location'],$info['id']],L('person.table.week_del_warn_two'))."<br>";
                        continue;
                    }
                    // 删除相关 附件
                    $result = $this->sqlFind("SELECT id, src FROM `file` WHERE targetId = '{$info['id']}' ");
                    foreach ($result as $file) {
                        delete([
                            'table' => 'file',
                            'where' => " id = '{$file['id']}'",
                        ]);
                        fileDelete($file['src']);
                    }
                    // 删除表
                    delete([
                        "table" => self::table,
                        "where" => $where
                    ]);
                    //添加记录
                    $text .= str_replace(['{{staffName}}','{{location}}','{{id}}'],[$this->control['name'],$info['location'],$info['id']],L('person.table.week_del_text')). '<br>';
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] =str_replace(['{{x}}'],[$x],L('person.table.week_del_mag'));
            $json['warn']     = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }
}
